package com.logica.mdm.webservices.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.logica.mdm.webservices.dao.SearchAddressDao;
import com.logica.mdm.webservices.dao.beans.AddressResultBean;

/**
 * Implementation using NamedParameterJdbcTemplate
 */
@Repository
public class JdbcSearchAddressDaoImpl implements SearchAddressDao {
	
	private NamedParameterJdbcTemplate jdbcTemplate;

	@Autowired
	public void setDataSource(DataSource dataSource) {
	    this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
	}
	
	@Override
	public List<AddressResultBean> searchAddressByParty(String sqlQuery, Map<String,?> sqlParams) {
		return this.jdbcTemplate.query(sqlQuery, sqlParams, new AddressMapper());
	}
	
	/**
	 * Inner class defining the mapping between the database and PartyRelResultBean
	 */
	private static final class AddressMapper implements RowMapper<AddressResultBean> {
		public AddressResultBean mapRow(ResultSet rs, int rowNum) throws SQLException {
			AddressResultBean address = new AddressResultBean();
			address.setAddressTypeDesc(rs.getString("ADDRESS_TYPE_DESC"));
			address.setAddressType(rs.getString("ADDRESS_TYPE"));
			address.setStreetNumber(rs.getString("STREET_NUMBER"));
			address.setStreetType(rs.getString("STREET_TYPE"));
			address.setStreetName(rs.getString("STREET_NAME"));
			address.setAddressLine2(rs.getString("ADDRESS_LINE_2"));
			address.setAddressLine3(rs.getString("ADDRESS_LINE_3"));
			address.setMailBoxNumber(rs.getString("MAIL_BOX_NUMBER"));
			address.setAddressLine5(rs.getString("ADDRESS_LINE_5"));
			address.setCityName(rs.getString("CITY_NAME"));
			address.setPostalCd(rs.getString("POSTAL_CD"));
			address.setCountryName(rs.getString("COUNTRY_NAME"));
			address.setCountryCode(rs.getString("COUNTRY_CODE"));
			address.setHexacleVoie(rs.getString("HEXACLE_VOIE"));
			address.setHexacleLocalite(rs.getString("HEXACLE_LOCALITE"));
			address.setMdmId(rs.getString("PARTY_ID"));
			return address;
		}
	}
}
